package huanzhao.erp.other.validator;

import huanzhao.erp.domain.annotation.CheckAssignable;
import huanzhao.erp.domain.entity.Staff;
import huanzhao.erp.domain.types.StaffType;
import huanzhao.erp.mapper.StaffMapper;
import huanzhao.erp.service.BasicService;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author April
 * 2024/7/24 下午6:34
 * @version 1.0
 */
@Component
public class StaffAssignableValidator implements ConstraintValidator<CheckAssignable, Long> {
    private final StaffMapper staffMapper;
    private final BasicService basicService;
    private StaffType staffType;

    public StaffAssignableValidator(StaffMapper staffMapper, BasicService basicService) {
        this.staffMapper = staffMapper;
        this.basicService = basicService;
    }

    @Override
    public void initialize(CheckAssignable constraintAnnotation) {
        this.staffType = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Long staffId, ConstraintValidatorContext constraintValidatorContext) {
        if (staffId == null) {
            return true;
        }
        Staff staff = staffMapper.selectById(staffId);
        if (staff == null) {
            return false;
        }
        String messageTemplate = null;
        if (staff.getResigned()) {
            messageTemplate = "员工已离职，不可分配任务！";
        } else if (staff.getVacating()) {
            messageTemplate = "员工正在休假，不可分配任务！";
        } else {
            switch (staffType) {
                case PURCHASER -> {
                    if (!staff.getPurchaser()) {
                        messageTemplate = "员工非采购员！";
                    }
                }
                case MAINTAINER -> {
                    if (!staff.getMaintainer()) {
                        messageTemplate = "员工非维修员！";
                    }
                }
                case WAREHOUSER -> {
                    if (!staff.getWarehouser()) {
                        messageTemplate = "员工非仓库员！";
                    }
                }
                case FINANCER -> {
                    Long financerId = basicService.getGlobalSetting().getFinancerId();
                    if (!staff.getId().equals(financerId)) {
                        messageTemplate = "员工非财务员！";
                    }
                }
            }

        }
        if (messageTemplate == null) {
            return true;
        }
        constraintValidatorContext.disableDefaultConstraintViolation();
        constraintValidatorContext.buildConstraintViolationWithTemplate(messageTemplate).addConstraintViolation();
        return false;
    }
}
